import 'package:bot_toast/bot_toast.dart';
import 'package:bruno/bruno.dart';
import 'package:file_picker/file_picker.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:get/get_state_manager/src/simple/get_controllers.dart';
import 'package:image_pickers/image_pickers.dart';
import '../../common/colors.dart';
import '../../router/app_pages.dart';
import '../../services/address.dart';
import '../../services/dio_manager.dart';
import 'dart:io';
import 'package:dio/dio.dart';
import 'package:get/route_manager.dart';

import '../personnel_module/personnel_model.dart';
import 'my_special_text_span_builder.dart';
class PublishedDailyController extends GetxController{
  List<BrnCommonActionSheetItem> actions = [];

  TextEditingController editingController = TextEditingController();

  final MySpecialTextSpanBuilder mySpecialTextSpanBuilder =
  MySpecialTextSpanBuilder();

  /// 控制表情隐藏还是显示
  bool isShowEmoji = false;

  GalleryMode _galleryMode = GalleryMode.image;

  // List<Media> listImagePaths = [];
  // List<Media> listVideoPaths = [];
  List listFilePaths = [];

  String? fileName;

  // Map fileParams = {};

  var focus_userIds;
  var personnelParams;


  /// 发送请求
  requestDataWithPublish() async {


    FormData? formData = FormData();

    if(listFilePaths.isEmpty){
      // print(personnelParams);
      if(focus_userIds==null){
        formData = FormData.fromMap({
          'content':editingController.text,
          'state':'未阅',
          'tomorrow_content':'',
        });
        var json = await DioManager().kkRequest(Address.reportCreate,
            bodyParams: formData,isShowLoad: true);
        if(json['errmsg']=='ok'){
          Get.back(result: 'refresh');
        }
        BotToast.showText(text: json['message']);
      }
      else{
        print('用户ID ============ ${focus_userIds.join(',')}');

        formData = FormData.fromMap({
          'content':editingController.text,
          'state':'未阅',
          'tomorrow_content':'',
          'focus_user':focus_userIds.join(','),
        });
        var json = await DioManager().kkRequest(Address.reportCreate,
            bodyParams: formData,isShowLoad: true);
        if(json['errmsg']=='ok'){
          Get.back(result: 'refresh');
        }
        BotToast.showText(text: json['message']);
      }
    }

    else if(listFilePaths.isNotEmpty){
      print('上传文件 ============ ${listFilePaths}');
      // print('用户ID ============ ${personnelParams['personnelIdArr']}');

      Map<String,dynamic> flMap = {};

      if(listFilePaths.isNotEmpty){
        for(int i = 0;i<listFilePaths.length;i++){
          print('${listFilePaths[i]['path']}');
          MultipartFile multipartFile = MultipartFile.fromFileSync(
            '${listFilePaths[i]['path']}',filename: '${listFilePaths[i]['name']}',
          );
          flMap['file'] = multipartFile;
          // flMap.addEntries()
          flMap['content'] = editingController.text;
          flMap['state'] = '未阅';
          flMap['tomorrow_content'] = '';
          flMap['focus_user'] = focus_userIds==null?'':'${focus_userIds.join(',')}';
          // flMap.addEntries([
          //   MapEntry('file', multipartFile),
          // ]);
          formData = FormData.fromMap(flMap);
          var json = await DioManager().kkRequest(Address.reportCreate,
              bodyParams: formData,isShowLoad: true);
          if(json['errmsg']=='ok'){
            // Get.back(result: 'refresh');
          }
          BotToast.showText(text: json['message']);
        }
        print('flMap ======== ${flMap}');
        Get.back(result: 'refresh');
      }
      print('flMap ======== ${flMap}');

    }

    // var json = await DioManager().kkRequest(Address.reportCreate,
    //     bodyParams: formData,isShowLoad: true);
    // if(json['errmsg']=='ok'){
    //   Get.back(result: 'refresh');
    // }
    // BotToast.showText(text: json['message']);

  }

  /// 点击附件icon
  tapClickAccessory(){
    // actions.clear();
    showModalBottomSheet(
        context: Get.overlayContext!,
        backgroundColor: Colors.transparent,
        builder: (BuildContext context) {
          return BrnCommonActionSheet(
            title: "",
            actions: actions,
            clickCallBack: (
                int index,
                BrnCommonActionSheetItem actionEle,
                )async {
              if (index == 0) {
                ImagePickers.openCamera(
                    cropConfig: CropConfig(
                        enableCrop: false,
                        width: 2,
                        height: 3))
                    .then((Media? media) {
                  // _listImagePaths.clear();
                  if (media != null) {

                    var fileParams = {
                      'name':'${media.path}',
                      'path':'${media.path}',
                    };

                    listFilePaths.add(fileParams);

                    print(listFilePaths);
                  }
                  update();
                });
              }
              if (index == 1) {
                ImagePickers.openCamera(
                    cameraMimeType:
                    CameraMimeType.video)
                    .then((media) {
                  // listFilePaths.clear();
                  if (media != null) {
                    print(media.path);
                    var fileParams = {
                      'name':'${media.path}',
                      'path':'${media.path}',
                    };

                    listFilePaths.add(fileParams);
                  }
                  update();
                });
              }
              if (index == 2) {
                selectImages();
              }
              if(index == 3){
                //往下开始用filepick提供的方法
                FilePickerResult? result = await FilePicker.platform.pickFiles(
                  type: FileType.any,
                  // allowedExtensions: ['text'],    //筛选文件类型
                );
                //这就用完了，下面就赋值了
                if (result != null) {
                  // listFilePaths.clear();
                  PlatformFile file = result.files.first;
                  print(result.files.first.path);
                 var fileParams = {
                    'name':'${file.name}',
                    'path':'${file.path}',
                  };

                  listFilePaths.add(fileParams);

                  // listFilePaths.add(file.path);
                  fileName = result.files.first.name;
                  update();
                } else {
                  // User canceled the picker
                }
              }
              // String title = actionEle.title;
              // BrnToast.show("title: $title, index: $index", context);
            },
          );
        });
    update();
  }
  /// 点击显示隐藏表情
  tapClickEmojiShow(){
    isShowEmoji=!isShowEmoji;
    print(isShowEmoji);
    update();
  }


  /// 跳转@页面
  tapClickPushAite()async{

    var params = {
      'isMultiple':true,
      'personnelIdArr':focus_userIds,
    };

   var data = await Get.toNamed(AppRoutes.personnel,arguments: params);
   if(data != null){
     // var params  = data;

     focus_userIds = data['personnelIdArr'];

     for(int i = 0;i<data['personnelNameArr'].length;i++){
       editingController.text = editingController.text + '@${data['personnelNameArr'][i]} '+' ';
     }

     // print('personnelParams++++++${personnelParams}');
     // personnelParams = params;
   }
   update();
  }
  ///选择图片
  Future<void> selectImages() async {
    try {
      _galleryMode = GalleryMode.image;

      // listFilePaths = await ImagePickers.pickerPaths(
      //   galleryMode: _galleryMode,
      //   showGif: false,
      //   selectCount: 1,
      //   showCamera: false,
      //   cropConfig: CropConfig(enableCrop: true, height: 1, width: 1),
      //   compressSize: 300,
      //   uiConfig: UIConfig(
      //     uiThemeColor: AppColor.themeColor,
      //   ),
      // );
      ImagePickers.pickerPaths(
          galleryMode: _galleryMode,
          showGif: false,
          selectCount: 1,
          showCamera: false,
          cropConfig: CropConfig(enableCrop: true, height: 1, width: 1),
          compressSize: 300,
          uiConfig: UIConfig(
            uiThemeColor: AppColor.themeColor,
          ),
      ).then((value) {
       var fileParams = {
          'name':'${value[0].path}',
          'path':'${value[0].path}',
        };
        listFilePaths.add(fileParams);
        update();
      });
      if (listFilePaths.length > 0) {
        listFilePaths.forEach((media) {
          print(media.path.toString());
        });
      }
     update();
    } on PlatformException {}
  }


  @override
  void onInit() {
    // TODO: implement onInit
    super.onInit();
    actions.add(BrnCommonActionSheetItem(
      '拍照',
      actionStyle: BrnCommonActionSheetItemStyle.normal,
    ));
    actions.add(BrnCommonActionSheetItem(
      '录视频',
      actionStyle: BrnCommonActionSheetItemStyle.normal,
    ));
    actions.add(BrnCommonActionSheetItem(
      '相册',
      actionStyle: BrnCommonActionSheetItemStyle.normal,
    ));
    actions.add(BrnCommonActionSheetItem(
      '文件',
      actionStyle: BrnCommonActionSheetItemStyle.normal,
    ));

  }

}